package com.xv.controller;

import com.xv.dao.UserMapper;
import com.xv.pojo.Msg;
import com.xv.pojo.User;
import com.xv.pojo.UserDTO;
import com.xv.pojo.UserExample;
import com.xv.service.UserServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;


@Controller
@Scope(value ="prototype")
public class UserController {
    @Autowired
    UserServiceImp userServiceImp;
    @Autowired
    UserMapper userMapper;
    @RequestMapping(value="/login",method= RequestMethod.POST)
    public String login(User user, Model model) throws Exception {
        user=userServiceImp.checkLogin(user.getUsername(), user.getPassword());
        if(null != user){
            model.addAttribute(user);
            return "list2";
        }
        return "redirect:/login.jsp";
    }

    @RequestMapping(value="/user/add",method= RequestMethod.POST)
    public String addUser(UserDTO userdto, Model model) throws Exception {
        User user = new User();
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(userdto.getUsername());
        List<User> userList = userMapper.selectByExample(example);
        if ( null != userList && userdto.getPassword().equals(userdto.getPassword2())) {
            user.setUsername(userdto.getUsername());
            user.setPassword(userdto.getPassword());
            userServiceImp.addUser(user);
        }
        return "redirect:/login.jsp";
    }
}
